package com.aloda.ojjudge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.aloda.ojcommon.constant.ErrorCode;
import com.aloda.ojcommon.exception.BaseException;
import com.aloda.ojjudge.codesandbox.CodeSandbox;
import com.aloda.ojjudge.pojo.dto.ExecuteCodeRequest;
import com.aloda.ojjudge.pojo.dto.ExecuteCodeResponse;
import com.aloda.ojjudge.properties.CodeSandboxProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author aloda
 * @Date 2025/4/29 15:32
 */
@Component
public class RemoteCodeSandbox implements CodeSandbox {

    @Resource
    private CodeSandboxProperties codeSandboxProperties;

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(codeSandboxProperties.getUrl())
                .header(codeSandboxProperties.getAuthHeader(), codeSandboxProperties.getAuthHeaderValue())
                .body(json)
                .execute()
                .body();
        if (StrUtil.isBlank(responseStr)) {
            throw new BaseException(ErrorCode.SYSTEM_ERROR.getCode(), "远程代码沙箱调用错误");
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
